<template>
  <div class="axiom-tag-input" @click="focusInput">
    <AxiomTag
      v-for="(tag, index) in tags"
      :key="index"
      closable
      @close="removeTag(index)"
    >
      {{ tag }}
    </AxiomTag>
    <input
      ref="inputRef"
      v-model="inputValue"
      class="tag-input-field"
      :placeholder="placeholder"
      @keydown.enter.prevent="addTag"
      @blur="addTag"
      @keydown.backspace="handleBackspace"
    />
  </div>
</template>

<script>
import { ref, watch, nextTick } from 'vue';
import AxiomTag from './AxiomTag.vue';

export default {
  name: 'AxiomTagInput',
  components: { AxiomTag },
  props: {
    modelValue: {
      type: Array,
      default: () => [],
    },
    placeholder: {
      type: String,
      default: '输入后按回车新增',
    },
    allowDuplicates: {
      type: Boolean,
      default: false,
    }
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const inputRef = ref(null);
    const inputValue = ref('');
    const tags = ref([...props.modelValue]);

    watch(() => props.modelValue, (newValue) => {
      if (JSON.stringify(newValue) !== JSON.stringify(tags.value)) {
        tags.value = [...newValue];
      }
    });

    const focusInput = () => {
      inputRef.value?.focus();
    };

    const addTag = () => {
      const newTag = inputValue.value.trim();
      if (newTag) {
        if (props.allowDuplicates || !tags.value.includes(newTag)) {
          tags.value.push(newTag);
          emit('update:modelValue', [...tags.value]);
        }
        inputValue.value = '';
      }
    };

    const removeTag = (index) => {
      tags.value.splice(index, 1);
      emit('update:modelValue', [...tags.value]);
    };

    const handleBackspace = () => {
      if (inputValue.value === '' && tags.value.length > 0) {
        removeTag(tags.value.length - 1);
      }
    };

    return {
      inputRef,
      inputValue,
      tags,
      focusInput,
      addTag,
      removeTag,
      handleBackspace,
    };
  },
};
</script>

<style lang="scss">
@use '../../styles/components/common/axiom-tag-input';
</style> 